#include "tim_app.h"


uint32_t ic_buffer[2][30];
int32_t ic_value[2];
int Freq[2];
int32_t cycle[2];
uint8_t PH_clock[2];//A,B
uint8_t PD_clock[2]; // A,B
uint32_t old_time[2];//A,B
uint32_t Freq_max_min_A[2];
uint32_t Freq_max_min_B[2];
void tim_ic_proc(void)
{
	ic_value[0] = ic_value[1] = 0;
	for(int i = 0; i<30;i++)
	{
		ic_value[0] += ic_buffer[0][i];
		ic_value[1] += ic_buffer[1][i];
	}
	ic_value[0] /= 30.0f;
	ic_value[1] /= 30.0f;

	ic_value[0] = 10000000.0f / (float)ic_value[0] + PX_T;
	ic_value[1] = 10000000.0f / (float)ic_value[1] + PX_T;

	if(ic_value[0] > 20000)
		ic_value[0] = 20000;
	if (ic_value[1] > 20000)
		ic_value[1] = 20000;

	cycle[0] = 1000000.0f / (float)ic_value[0] ;
	cycle[1] = 1000000.0f / (float)ic_value[1]	;

	Freq[0] = ic_value[0];
	Freq[1] = ic_value[1] ;

	if(Freq[0] > PH_T)
	{
		if(!PH_clock[0])
		{
			NA[1]++;
			PH_clock[0] = 1;
		}

	}
	else
	{
		PH_clock[0] = 0;
	}

	if (Freq[1] > PH_T)
	{
		if (!PH_clock[1])
		{
			NB[1]++;
			PH_clock[1] = 1;
		}
	}
	else
	{
		PH_clock[1] = 0;
	}

	uint32_t now_time = HAL_GetTick();
	if(now_time >= old_time[0] + 3000)
	{
		PD_clock[0] = 0;
		old_time[0] = now_time;
		Freq_max_min_A[0] = Freq[0];
		Freq_max_min_A[1] = Freq[0];
	}
	else
	{
		if (Freq_max_min_A[0]<Freq[0])
		{
			Freq_max_min_A[0] = Freq[0];
		}
		if(Freq_max_min_A[1]>Freq[0])
		{
			Freq_max_min_A[1] = Freq[0];
		}

		if (Freq_max_min_A[0] - Freq_max_min_A[1] > PD_T && !PD_clock[0])
		{
			PD_clock[0] = 1;
			NA[0]++;
		}
	}

	if (now_time >= old_time[1] + 3000)
	{
		PD_clock[1] = 0;
		old_time[1] = now_time;
		Freq_max_min_B[0] = Freq[1];
		Freq_max_min_B[1] = Freq[1];
	}
	else
	{
		if (Freq_max_min_B[0] < Freq[1])
		{
			Freq_max_min_B[0] = Freq[1];
		}
		if (Freq_max_min_B[1] > Freq[1])
		{
			Freq_max_min_B[1] = Freq[1];
		}

		if (Freq_max_min_B[0] - Freq_max_min_B[1] > PD_T && !PD_clock[1])
		{
			PD_clock[1] = 1;
			NB[0]++;
		}
	}
}
